package com.xyh.aspect;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.xyh.web.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void deBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String className = joinPoint.getSignature().getDeclaringType() + "." + joinPoint.getSignature().getName();//类名方法名
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog= new RequestLog(uri, ip, className, args);
        logger.info("Request : {}", requestLog);
    }
    @After("log()")
    public void deAfter() {
//        logger.info("--------deAfter--------");
    }
    @AfterReturning(returning = "result",pointcut = "log()")
    public void deAfterReturn(Object result){
        logger.info("Result:{}",result);
    }
    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    @Accessors(chain = true)
    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;
    }
}
